# coding:utf-8
# https://www.cnblogs.com/zhiyiYo/p/15676079.html
import sys
from datetime import datetime
import pytz
from PyQt5.QtCore import Qt, pyqtSignal, QThread, QMutex, QDateTime, QTimer
from PyQt5.QtGui import QKeySequence, QFont, QPainter
from PyQt5.QtWidgets import QWidget, QShortcut, QApplication

from serialPort import cm3_pb2

from windowUI.temperatureUI import Ui_Temperature


class TemperatureWindow(QWidget, Ui_Temperature):
    """ 图片查看器 """
    # 声明带一个字典类型参数的信号
    temperatureSignal = pyqtSignal(dict)  # 主界面的信号用来绑定子界面类的函数方法

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)
        # 引入公共程序
        from utils.common import commonProgram
        # 引入Sqlite3记录模块
        timeStr = datetime.now(pytz.timezone('Asia/Shanghai')).strftime("%m-%d_%H-%M")
        self.sqlite3Handler = commonProgram.EnableSqlite3Handler(db_path='./data/records/',
                                                                 db_name=f'tempLog_{timeStr}_BoevxaDb.db')
        # self.sqlite3Handler.InsertSingleData(signal=1, count=10, points='(1,3)/(2,4)/(3,4)/')
        # 引入可控串口信息窗口
        commonProgram.EnableSerialPort(winSignal=self.temperatureSignal, RecvSerialData=self.RecvSerialData)
        # 快捷键
        self.ShortcutFun()

        # 初始化小部件
        self.__initWidget()

    def ParseTempFun(self, bytes_data):
        hex_temp = b'0000000000000000'
        dec_temp = b'00000000'
        brightness = b'00000000'
        idx = -1
        for item in bytes_data:
            # print(hex(item), bin(item))
            idx += 1
            if idx % 4 == 0:
                hex_temp = (item << 8)
                # print('hex_temp1', hex_temp)
            elif idx % 4 == 1:
                hex_temp = hex_temp + item
                # print('hex_temp2', hex_temp)
            elif idx % 4 == 2:
                dec_temp = int(item)
            elif idx % 4 == 3:
                brightness = int(item)
        return hex_temp, dec_temp, brightness

    def RecvSerialData(self, dataDict: dict):
        typeStr = dataDict.get('type', 'null').strip()
        if typeStr == 'rece_protobuf':
            display = dataDict.get('data', '')
            if display.msg_type == cm3_pb2.Temperature:
                tempValue = self.ParseTempFun(display.temperature)
                # print(tempValue)
                hex_temp = tempValue[0]
                dec_temp = tempValue[1]
                brightness = tempValue[2]
                self.newID = self.sqlite3Handler.InsertTempLog(hex_temp=hex_temp, dec_temp=dec_temp,
                                                               brightness=brightness)
                self.labelID.setText(str(self.newID))
                self.lcdHex.display(hex_temp)
                self.lcdDec.display(dec_temp)
                # 指定Tokyo时区当前时间
                timeStr = datetime.now(pytz.timezone('Asia/Shanghai')).strftime("%Y-%m-%d %H:%M:%S.%f")
                self.labelTime.setText(timeStr)
                self.labelBrightness.setText(str(brightness))
        elif typeStr == 'statusbar':
            dataStr = dataDict.get('data', '')
            self.labelStatus.setText(dataStr)

    def ShortcutFun(self):
        # 快捷键 F11
        # 全屏
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               双击 或者 F11')

    def WindowSizeFun(self):
        # print(toStatus)
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'

    def __initWidget(self):
        """ 初始化小部件 """
        pass


if __name__ == '__main__':
    # QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    # QApplication.setAttribute( Qt.AA_Use96Dpi)
    app = QApplication(sys.argv)
    font = QFont("宋体")
    pointsize = font.pointSize()
    font.setPixelSize(int(pointsize * 90 / 72))
    app.setFont(font)
    # myWin = MyMainWindow()
    myWin = TemperatureWindow()
    # 首先设置接收触控事件
    # w.setAttribute(Qt.WA_AcceptTouchEvents, True)
    myWin.show()
    sys.exit(app.exec_())
